package com.lc.utils;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by lichao on 2017/5/5.
 */
public class Util {
        public static String map2UrlString(Map<String, ? extends Object> paramsMap) {
            String paramString = "";
            Set<String> keys = paramsMap.keySet();
            for (String key : keys) {
                Object value = paramsMap.get(key);
                if (value != null) {
                    try {
                        paramString += key + "="
                                + URLEncoder.encode(value.toString(), "UTF-8")
                                + "&";
                        // paramString += key + "=" + value.toString() + "&";
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            return paramString;
        }

        public static Map<String, String> query2ParamsMap(String queryString) {
            Map<String, String> paramsMap = new HashMap<String, String>();
            if (queryString == null || "".equals(queryString)) {
                return null;
            }

            String[] params = queryString.split("&");

            for (String param : params) {
                String key = param.substring(0, param.indexOf("="));
                String value = param.substring(param.indexOf("=") + 1,
                        param.length());
                try {
                    paramsMap.put(key, URLDecoder.decode(value, "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            return paramsMap;
        }

        public static String getRndPlainText(int textLenth) {
            StringBuffer buffer = new StringBuffer(
                    "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
            StringBuffer sb = new StringBuffer();
            Random r = new Random();
            int range = buffer.length();
            for (int i = 0; i < textLenth; i++) {
                // 生成指定范围类的随机数0—字符串长度(包括0、不包括字符串长度)
                sb.append(buffer.charAt(r.nextInt(range)));
            }
            return sb.toString();
        }

        public static String getRndNumber(int textLenth) {
            StringBuffer buffer = new StringBuffer("0123456789");
            StringBuffer sb = new StringBuffer();
            Random r = new Random();
            int range = buffer.length();
            for (int i = 0; i < textLenth; i++) {
                // 生成指定范围类的随机数0—字符串长度(包括0、不包括字符串长度)
                sb.append(buffer.charAt(r.nextInt(range)));
            }
            return sb.toString();
        }

        public static String getRemoteAddr(HttpServletRequest request) {
            try {
                String remoteIp = request.getHeader("X-Forwarded-For");
                if (!StringUtils.isBlank(remoteIp)) {
                    return remoteIp.split("[,]")[0];
                }
                remoteIp = request.getHeader("X-Real-IP");
                if (!StringUtils.isBlank(remoteIp)) {
                    return remoteIp;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return request.getRemoteAddr();
        }

        public static long generateTradeId(long now) {
            Random random = new Random();
            int rndInt = random.nextInt(9999 - 1000) + 1000;
            return Long.valueOf(now + "" + rndInt);
        }

        public static void main(String[] args) {
            System.out.println(stringToDateForUsage("30日 203400"));
        }

        // 1日 203400
        public static Date stringToDateForUsage(String time) {
            if (StringUtils.isBlank(time)) {
                return null;
            }
            if (time.indexOf("日") != -1) {
                int opDay = Integer.parseInt(time.substring(0, time.indexOf("日")));

                Calendar calendar = Calendar.getInstance();
                int day = calendar.get(Calendar.DAY_OF_MONTH);

                int opYear = calendar.get(Calendar.YEAR);
                int opMonth = calendar.get(Calendar.MONTH) + 1;

                // 是上个月
                if (opDay > day) {
                    if (opMonth > 1) {
                        opMonth = opMonth - 1;
                    } else {
                        opMonth = 12;
                        opYear = opYear - 1;
                    }
                }

                time = time.substring(time.indexOf("日") + 1);
                time = time.trim();

                String prefix = "" + opYear;
                if (opMonth < 10) {
                    prefix = prefix + "0" + opMonth;
                } else {
                    prefix = prefix + opMonth;
                }
                if (opDay < 10) {
                    prefix = prefix + "0" + opDay;
                } else {
                    prefix = prefix + opDay;
                }

                time = prefix + " " + time;
                return stringToDate(time, "yyyyMMdd HHmmss");
            } else {
                return stringToDate(time, "yyyyMMdd HHmmss");
            }

        }

        public static String dateToStringCommon(Date date) {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return df.format(date);
        }

        public static String dateToString(Date date, String format) {
            SimpleDateFormat df = new SimpleDateFormat(format);
            return df.format(date);
        }

        public static Date stringToDate(String time, String pattern) {
            SimpleDateFormat df = new SimpleDateFormat(pattern);
            try {
                return df.parse(time);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }

        public static String getHost(String url) {
            try {
                URL urlObj = new URL(URLDecoder.decode(url));
                return urlObj.getHost();
            } catch (Throwable e) {
                e.printStackTrace();
            }
            return "";
        }

        public static int parseInt(String str) {
            if (StringUtils.isBlank(str)) {
                return 0;
            }
            try {
                return Integer.parseInt(str);
            } catch (Throwable e) {
                return 0;
            }
        }

        public static long parseLong(String str) {
            if (StringUtils.isBlank(str)) {
                return 0;
            }
            try {
                return Long.parseLong(str);
            } catch (Throwable e) {
                return 0;
            }
        }

        public static int getBalance(Date startTime, Date stopTime) {
            long seconds = (stopTime.getTime() - startTime.getTime()) / 1000;
            int balance = (int) Math.ceil(seconds / 60.0);
            return balance;
        }

        public static String pasName(String name){
            String [] a = name.split("[.]");
            name = a[a.length-1];
            return name;
        }
}
